package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.Advice;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.service.mongo.AdviceService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * 反馈Advice实现类
 */
@Service
public class AdviceServiceImpl implements AdviceService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 分页查询所有反馈信息：
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageBeanVo findAdviceList(Integer pageNum, Integer pageSize) {

        int startIndex = (pageNum-1) * pageSize;
        //1.根据userId 查询 advice
        Query query = new Query()
                .skip(startIndex).limit(pageSize);

        List<Advice> adviceList = mongoTemplate.find(query, Advice.class);

        //查询总记录数
        long counts = mongoTemplate.count(query, Advice.class);
        //3.构建返回值
        return new PageBeanVo(pageNum , pageSize , counts ,  adviceList);
    }

    /**
     * 保存反馈
     * @param advice
     */
    @Override
    public void save(Advice advice) {

        mongoTemplate.save(advice);
    }


    /**
     * 删除反馈
     */
    @Override
    public void delete(Long userId) {

        Query query = new Query(
                Criteria.where("userId").is(userId)
        );
        mongoTemplate.remove(query, Advice.class);
    }

    /**
     * 回显反馈
     * @return
     */
    @Override
    public Advice findById(Long userId) {

        Query query = new Query(
                Criteria.where("userId").is(userId)
        );
        Advice advice = mongoTemplate.findOne(query, Advice.class);
        return advice;
    }

}
